package com.ia2014.tp.portal2.log;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import com.ia2014.tp.portal2.integration.converters.Parser;

import webservices.WSMonitoreoServiceLocator;
import webservices.WSMonitoreo;


import com.ia2014.tp.portal2.utils.Helper;

	public class LogsLogisticaMonitoreo {
		
		private static Logger logger = PortalLogger.getLogger(LogsLogisticaMonitoreo.class.toString());
		
		// Set up all the default values
	    private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
	    //private static final String DEFAULT_DESTINATION = "jms/queue/monitoreo";
	    //private static final String DEFAULT_USERNAME = "monitoreo";
	    //private static final String DEFAULT_PASSWORD = "monitoreo1.0";
	    private static final String INITIAL_CONTEXT_FACTORY =  "org.jboss.naming.remote.client.InitialContextFactory";
	    //private static final String PROVIDER_URL = "remote://localhost:4447";
	    
		
	       
		public static String logMessage(String message){
			
			
			String resultado = "";
			try{
			
				//verifica si el envio del Log de Auditoria el modulo de Logistica y monitoreo 
				//debe ser a traves del metodo sincronico o asincronico
				boolean async = Helper.getEnvioAsyncLogLogidaMonitoreo() ;

				if(async){
					//Metodo asincronico de log de logistica y monitoreo
					System.out.println("Metodo asincronico de log de logistica y monitoreo");
					logAsync(message);			
				}else{
					//Metodo sincronico de log de logistica y Monitoreo
					//retorna un "OK" o "ERROR" desde WS
					System.out.println("Metodo sincronico de log de logistica y Monitoreo");
					resultado = logSync(message);
				}
			}
			catch (Exception ex){
				logger.error("Error al tratar de determinar la forma de informar el Log al Modulo de Monitoreo y Logistica");
				logger.error(ex.toString());
				logger.debug("Stacktrace", ex);
			}
			return resultado;
		}
		
		
		private static String logSync(String message){
			String respuesta = "";
			String xml;
			
			Parser parser = new Parser();
			
			try {
				
				xml = parser.getXmlLogLogisticaMonitoreo(message);			
				
				System.out.println("Mensaje a enviar: " + xml);
				
				System.out.println("Creando Cliente WebService...");
			       
				System.out.println("Conectando al WebService: " + Helper.getURLWebServiceConfirmacionVentaLogisticaMonitoreo());
		       
				/*
				URL url = null;
				
		        url = new URL(Helper.getURLWebServiceLogLogisticaMonitoreo());
		        		
				WSMonitoreoService service = new WSMonitoreoService(url);
				
				WSMonitoreo port = service.getWSMonitoreoPort();
				
				respuesta = port.enviarInformeAuditoria(xml);
				*/
	
				WSMonitoreoServiceLocator service = new WSMonitoreoServiceLocator();
				
				WSMonitoreo port = service.getWSMonitoreoPort();
				
				respuesta = port.enviarInformeAuditoria(xml);
				
				System.out.println(respuesta);
				
				return parser.getResponse(respuesta).getEstado();
			
			}
			catch (Exception e) {			
				
				logger.error("Error al tratar de enviar el Log al Modulo de Logistica y Monitoreo.");
				logger.error(e.toString());
				logger.debug("Stacktrace", e);
			}
			
			return "ERROR";
			
		}
		
		
		
		private static String logAsync(String message){
			
			String resultado = "OK";
			
			ConnectionFactory connectionFactory = null;
	        Connection connection = null;
	        Session session = null;
	        MessageProducer producer = null;
	        Destination destination = null;
	        Context context = null;
	        
	        String json;
			Parser parser= new Parser();

	        // Set up the context for the JNDI lookup
	        final Properties env = new Properties();
	        
	        env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
	        env.put(Context.PROVIDER_URL, Helper.getURLQueueLogLogisticaMonitoreo());
	        //env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username",  Helper.getUserQueueLogLogisticaMonitoreo()));
	        //env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password",  Helper.getPasswordQueueLogLogisticaMonitoreo()));
	        
	        try {
	        	
				context = new InitialContext(env);
				
				// Perform the JNDI lookups
		        String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
		        
		        connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
		        
		        String destinationString = System.getProperty("destination", Helper.getQueueLogLogisticaMonitoreo());
		        
		        destination = (Destination) context.lookup(destinationString);	        
			
		        
		        if ((Helper.getUserQueueLogLogisticaMonitoreo() != "") && 
		        	(Helper.getPasswordQueueLogLogisticaMonitoreo()!= "")){
		        	
		        	connection = connectionFactory.createConnection(System.getProperty("username", Helper.getUserQueueLogLogisticaMonitoreo()), 
						System.getProperty("password", Helper.getPasswordQueueLogLogisticaMonitoreo()));
		        }
		        else {
		        	connection = connectionFactory.createConnection();
		        }
		        
				session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
				
				producer = session.createProducer(destination);
				connection.start();
				
				// crear un mensaje de tipo text y setearle el contenido
				TextMessage mensajeJSON = session.createTextMessage();
				
				json = parser.getXmlLogLogisticaMonitoreo(message);			
				
				mensajeJSON.setText(json);
				
				System.out.println("Enviando LOG a traves de JMS al Monitor");
				//System.out.println(mensajeJSON);
				
				// enviar el mensaje
				producer.send(mensajeJSON);
				
				connection.close();
				
				System.out.println("LOG enviado a traves de JMS al Monitor");
				
			} catch (JMSException e) {
				logger.error(e.getMessage());
				logger.error(e.toString());
				resultado = "ERROR";
				
			}catch (NamingException e) {
				logger.error("Error al tratar de ubicar la Queue de mensajes de Logs\n " + Helper.getURLQueueLogLogisticaMonitoreo() +  " - "  + Helper.getQueueLogLogisticaMonitoreo());
				logger.error(e.toString());
				logger.debug("Stacktrace", e);
				resultado = "ERROR";
			}
	        catch(Exception ex){
				logger.error("Error al llamar a la Queue de mensajes de Logs\n " + Helper.getURLQueueLogLogisticaMonitoreo() +  " - "  + Helper.getQueueLogLogisticaMonitoreo());
				logger.error(ex.toString());
				logger.debug("Stacktrace", ex);		
				resultado = "ERROR";			
			}
	        
	        return resultado;
		}
		

	}
